﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using WebSite1.DataSet1TableAdapters;


namespace WebSite1
{
    public class fbresponse
    {
        public string id { get; set; }
        public string name { get; set; }
        public string first_name{ get; set; }
        public string last_name { get; set; }
    }
    public partial class registerfromfb : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["code"] == null)
            {
                return;
            }
            Uri uri = new Uri("https://graph.facebook.com/oauth/access_token?client_id=188715331198022&redirect_uri=http://bestgifts4.us/registerfromfb.php&client_secret=47b66709d0fded0d727b615aa7faeda2&code=" + Request["code"]);
            WebRequest http = HttpWebRequest.Create(uri);
            HttpWebResponse response = (HttpWebResponse)http.GetResponse();
            StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);

            String result = stream.ReadToEnd();
            response.Close();
            stream.Close();
            Uri uri1 = new Uri("https://graph.facebook.com/me?" + result);
            WebRequest http1 = HttpWebRequest.Create(uri1);
            response = (HttpWebResponse)http1.GetResponse();
            //StreamReader stream1 = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);

            //String result1 = stream1.ReadToEnd();
            
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(fbresponse));
            fbresponse f = (fbresponse)ser.ReadObject(response.GetResponseStream());
            
            DataSet1 a = new DataSet1();
            Generic_Data_Cheker gench = new Generic_Data_Cheker();
            var user_id = gench.GetFBUser(f.id);
            if (user_id == null)
            {
                fb_usersTableAdapter fbadap = new fb_usersTableAdapter();
                usersTableAdapter useradap = new usersTableAdapter();
                int newuserid = (int)gench.UserIDIdentity("", "", "", "", "", "", f.first_name, f.last_name, "FROM FACEBOOK");
                fbadap.Insert(f.id, newuserid, f.name);
                Session["UserID"] = newuserid.ToString();
            }
            else
            {
                Session["UserID"] = user_id.ToString();
            
            }
            Response.Redirect("/wed.aspx");
            //GetFBUser();


        }
    }
}